<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>财务统计 - 系统管理</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.0/dist/echarts.min.js"></script>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background-color: #f8f9fa;
        }
        .card {
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }
        .card-header {
            background-color: #4a6fa5;
            color: white;
            font-weight: 600;
            border-radius: 8px 8px 0 0;
        }
        .form-label {
            font-weight: 500;
            color: #495057;
        }
        .btn-primary {
            background-color: #4a6fa5;
            border-color: #4a6fa5;
        }
        .btn-primary:hover {
            background-color: #3d5b8c;
            border-color: #3d5b8c;
        }
        .summary-item {
            padding: 12px;
            background-color: #f8f9fa;
            border-radius: 6px;
            margin-bottom: 10px;
        }
        .summary-label {
            color: #6c757d;
            font-size: 14px;
        }
        .summary-value {
            color: #4a6fa5;
            font-weight: 600;
            font-size: 16px;
        }
        .chart-container {
            height: 400px;
            width: 100%;
        }
        .stats-card {
            border-left: 4px solid #4a6fa5;
        }
        .income-color {
            color: #28a745;
        }
        .expense-color {
            color: #dc3545;
        }
        .balance-color {
            color: #17a2b8;
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <div class="row align-items-center justify-content-between">
                            <div class="col">
                                <h3 class="mb-0">财务统计概览</h3>
                            </div>
                            <div class="col-auto">
                                <div class="row g-2 align-items-center">
                                    <div class="col-auto">
                                        <label for="dateRange" class="form-label mb-0">日期范围</label>
                                    </div>
                                    <div class="col-auto">
                                        <input type="date" id="startDate" class="form-control form-control-sm">
                                    </div>
                                    <div class="col-auto">
                                        <span>至</span>
                                    </div>
                                    <div class="col-auto">
                                        <input type="date" id="endDate" class="form-control form-control-sm">
                                    </div>
                                    <div class="col-auto">
                                        <div class="btn-group" role="group" aria-label="统计周期">
                                            <button type="button" class="btn btn-sm btn-outline-primary active" data-group="1">日</button>
                                            <button type="button" class="btn btn-sm btn-outline-primary" data-group="2">月</button>
                                            <button type="button" class="btn btn-sm btn-outline-primary" data-group="3">年</button>
                                        </div>
                                    </div>
                                    <div class="col-auto">
                                        <button type="button" class="btn btn-sm btn-primary" id="refreshBtn">刷新数据</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <!-- 财务摘要卡片 -->
                        <div class="row mb-4">
                            <div class="col-md-4">
                                <div class="card stats-card">
                                    <div class="card-body">
                                        <div class="summary-label">总收入</div>
                                        <div class="summary-value income-color" id="totalIncome">¥ 0.00</div>
                                        <div class="text-xs text-muted mt-1"><span id="incomeChange" class="income-color">+0.00%</span> 较上期</div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="card stats-card">
                                    <div class="card-body">
                                        <div class="summary-label">总支出</div>
                                        <div class="summary-value expense-color" id="totalExpense">¥ 0.00</div>
                                        <div class="text-xs text-muted mt-1"><span id="expenseChange" class="expense-color">+0.00%</span> 较上期</div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="card stats-card">
                                    <div class="card-body">
                                        <div class="summary-label">净收益</div>
                                        <div class="summary-value balance-color" id="netIncome">¥ 0.00</div>
                                        <div class="text-xs text-muted mt-1"><span id="netChange" class="balance-color">+0.00%</span> 较上期</div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 收入支出趋势图 -->
                        <div class="card mb-4">
                            <div class="card-header">
                                <h4 class="mb-0">收入支出趋势</h4>
                            </div>
                            <div class="card-body">
                                <div id="trendChart" class="chart-container"></div>
                            </div>
                        </div>

                        <div class="row">
                            <!-- 收入明细饼图 -->
                            <div class="col-md-6">
                                <div class="card h-100">
                                    <div class="card-header">
                                        <h4 class="mb-0">收入明细分析</h4>
                                    </div>
                                    <div class="card-body">
                                        <div id="incomePieChart" class="chart-container"></div>
                                    </div>
                                </div>
                            </div>
                            <!-- 支出明细饼图 -->
                            <div class="col-md-6">
                                <div class="card h-100">
                                    <div class="card-header">
                                        <h4 class="mb-0">支出明细分析</h4>
                                    </div>
                                    <div class="card-body">
                                        <div id="expensePieChart" class="chart-container"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 交易明细表格 -->
                <div class="card">
                    <div class="card-header">
                        <div class="row align-items-center justify-content-between">
                            <div class="col">
                                <h3 class="mb-0">交易明细</h3>
                            </div>
                            <div class="col-auto">
                                <div class="btn-group" role="group" aria-label="交易类型筛选">
                                    <button type="button" class="btn btn-sm btn-outline-primary active" data-type="all">全部</button>
                                    <button type="button" class="btn btn-sm btn-outline-success" data-type="income">收入</button>
                                    <button type="button" class="btn btn-sm btn-outline-danger" data-type="expense">支出</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>交易时间</th>
                                        <th>交易类型</th>
                                        <th>交易描述</th>
                                        <th>金额</th>
                                        <th>状态</th>
                                        <th>交易流水号</th>
                                    </tr>
                                </thead>
                                <tbody id="transactionRecords">
                                    <!-- 交易记录将通过JS动态加载 -->
                                    <tr>
                                        <td colspan="6" class="text-center">
                                            <div class="spinner-border" role="status">
                                                <span class="visually-hidden">加载中...</span>
                                            </div>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <div class="d-flex justify-content-center mt-4">
                            <nav aria-label="Page navigation">
                                <ul class="pagination" id="pagination">
                                    <!-- 分页将通过JS动态加载 -->
                                </ul>
                            </nav>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化变量
            let currentPage = 1;
            let totalPages = 1;
            let groupType = 1;
            let transactionType = 'all';
            let trendChart = null;
            let incomePieChart = null;
            let expensePieChart = null;
            
            // 设置默认日期范围（最近30天）
            const endDate = new Date();
            const startDate = new Date();
            startDate.setDate(startDate.getDate() - 29);
            document.getElementById('startDate').valueAsDate = startDate;
            document.getElementById('endDate').valueAsDate = endDate;
            
            // 从URL参数或localStorage获取token
            function getToken() {
                try {
                    // 首先从URL参数中获取token
                    const urlParams = new URLSearchParams(window.location.search);
                    const urlToken = urlParams.get('token');
                    
                    if (urlToken) {
                        // 将URL中的token存储到localStorage
                        localStorage.setItem('token', urlToken);
                        return urlToken;
                    }
                    
                    // 然后从localStorage中获取token
                    const storageToken = localStorage.getItem('token');
                    if (storageToken) {
                        return storageToken;
                    }
                    
                    // 如果都没有，则重定向到登录页面
                    window.location.href = '/login';
                    return null;
                } catch (error) {
                    console.error('获取token时发生错误:', error);
                    window.location.href = '/login';
                    return null;
                }
            }

            // 处理Token过期
            function handleTokenExpiration() {
                console.log('Token已过期或无效，请重新登录');
                alert('您的会话已过期，请重新登录');
                window.location.href = '/login';
            }
            
            // 初始化图表
            initCharts();
            
            // 加载财务数据
            loadFinancialData();
            
            // 加载交易记录
            loadTransactionRecords();
            
            // 统计周期切换
            document.querySelectorAll('.btn-group [data-group]').forEach(btn => {
                btn.addEventListener('click', function() {
                    // 移除所有活跃状态
                    document.querySelectorAll('.btn-group [data-group]').forEach(b => b.classList.remove('active'));
                    // 添加当前活跃状态
                    this.classList.add('active');
                    // 设置分组类型
                    groupType = parseInt(this.getAttribute('data-group'));
                    // 重新加载统计数据
                    loadFinancialData();
                });
            });
            
            // 交易类型筛选
            document.querySelectorAll('.btn-group [data-type]').forEach(btn => {
                btn.addEventListener('click', function() {
                    // 移除所有活跃状态
                    document.querySelectorAll('.btn-group [data-type]').forEach(b => b.classList.remove('active'));
                    // 添加当前活跃状态
                    this.classList.add('active');
                    // 设置交易类型
                    transactionType = this.getAttribute('data-type');
                    // 重置页码
                    currentPage = 1;
                    // 重新加载交易记录
                    loadTransactionRecords();
                });
            });
            
            // 刷新按钮点击事件
            document.getElementById('refreshBtn').addEventListener('click', function() {
                loadFinancialData();
                currentPage = 1;
                loadTransactionRecords();
            });
            
            // 初始化所有图表
            function initCharts() {
                // 初始化趋势图
                trendChart = echarts.init(document.getElementById('trendChart'));
                const trendOption = {
                    tooltip: {
                        trigger: 'axis',
                        formatter: function(params) {
                            let result = params[0].name + '<br/>';
                            params.forEach(param => {
                                result += param.marker + param.seriesName + ': ¥' + param.value + '<br/>';
                            });
                            return result;
                        }
                    },
                    legend: {
                        data: ['收入', '支出']
                    },
                    xAxis: {
                        type: 'category',
                        data: [],
                        axisLabel: {
                            rotate: 45
                        }
                    },
                    yAxis: {
                        type: 'value',
                        name: '金额（元）'
                    },
                    series: [
                        {
                            name: '收入',
                            data: [],
                            type: 'line',
                            smooth: true,
                            itemStyle: {
                                color: '#28a745'
                            },
                            areaStyle: {
                                color: {
                                    type: 'linear',
                                    x: 0, y: 0, x2: 0, y2: 1,
                                    colorStops: [{
                                        offset: 0, color: 'rgba(40, 167, 69, 0.3)'
                                    }, {
                                        offset: 1, color: 'rgba(40, 167, 69, 0.05)'
                                    }]
                                }
                            }
                        },
                        {
                            name: '支出',
                            data: [],
                            type: 'line',
                            smooth: true,
                            itemStyle: {
                                color: '#dc3545'
                            },
                            areaStyle: {
                                color: {
                                    type: 'linear',
                                    x: 0, y: 0, x2: 0, y2: 1,
                                    colorStops: [{
                                        offset: 0, color: 'rgba(220, 53, 69, 0.3)'
                                    }, {
                                        offset: 1, color: 'rgba(220, 53, 69, 0.05)'
                                    }]
                                }
                            }
                        }
                    ]
                };
                trendChart.setOption(trendOption);
                
                // 初始化收入饼图
                incomePieChart = echarts.init(document.getElementById('incomePieChart'));
                const incomePieOption = {
                    tooltip: {
                        trigger: 'item',
                        formatter: '{a} <br/>{b}: {c} ({d}%)'
                    },
                    legend: {
                        orient: 'vertical',
                        left: 'left'
                    },
                    series: [
                        {
                            name: '收入来源',
                            type: 'pie',
                            radius: '60%',
                            data: [],
                            emphasis: {
                                itemStyle: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            }
                        }
                    ]
                };
                incomePieChart.setOption(incomePieOption);
                
                // 初始化支出饼图
                expensePieChart = echarts.init(document.getElementById('expensePieChart'));
                const expensePieOption = {
                    tooltip: {
                        trigger: 'item',
                        formatter: '{a} <br/>{b}: {c} ({d}%)'
                    },
                    legend: {
                        orient: 'vertical',
                        left: 'left'
                    },
                    series: [
                        {
                            name: '支出类型',
                            type: 'pie',
                            radius: '60%',
                            data: [],
                            emphasis: {
                                itemStyle: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            }
                        }
                    ]
                };
                expensePieChart.setOption(expensePieOption);
                
                // 响应式调整
                window.addEventListener('resize', function() {
                    trendChart.resize();
                    incomePieChart.resize();
                    expensePieChart.resize();
                });
            }
            
            // 加载财务数据
            async function loadFinancialData() {
                try {
                    const token = getToken();
                    if (!token) return;
                    
                    const startDate = document.getElementById('startDate').value;
                    const endDate = document.getElementById('endDate').value;
                    
                    console.log('加载财务统计数据，时间范围:', startDate, '到', endDate);
                    console.log('分组类型:', groupType);
                    
                    const baseUrl = window.location.origin;
                    const apiUrl = `${baseUrl}/v1/finance/stats?start_time=${startDate}&end_time=${endDate}&group_type=${groupType}`;
                    console.log('API调用路径:', apiUrl);
                    
                    const response = await fetch(apiUrl, {
                        headers: {
                            'x-token': token,
                            'Content-Type': 'application/json'
                        }
                    });
                    
                    if (!response.ok) {
                        if (response.status === 401) {
                            handleTokenExpiration();
                            return;
                        }
                        throw new Error(`获取财务数据失败，状态码: ${response.status}`);
                    }
                    
                    const data = await response.json();
                    
                    // 处理响应数据
                    const chartData = data.data || data;
                    
                    // 更新财务摘要
                    document.getElementById('totalIncome').textContent = `¥ ${formatNumber(chartData.total_income || 0)}`;
                    document.getElementById('totalExpense').textContent = `¥ ${formatNumber(chartData.total_expense || 0)}`;
                    document.getElementById('netIncome').textContent = `¥ ${formatNumber((chartData.total_income || 0) - (chartData.total_expense || 0))}`;
                    
                    // 更新趋势图
                    trendChart.setOption({
                        xAxis: {
                            data: chartData.time_axis || []
                        },
                        series: [
                            {
                                name: '收入',
                                data: chartData.income_data || []
                            },
                            {
                                name: '支出',
                                data: chartData.expense_data || []
                            }
                        ]
                    });
                    
                    // 更新收入饼图
                    incomePieChart.setOption({
                        series: [{
                            data: chartData.income_breakdown || []
                        }]
                    });
                    
                    // 更新支出饼图
                    expensePieChart.setOption({
                        series: [{
                            data: chartData.expense_breakdown || []
                        }]
                    });
                    
                } catch (error) {
                    console.error('加载财务数据失败:', error);
                    alert(`加载财务数据失败: ${error.message}`);
                }
            }
            
            // 加载交易记录
            async function loadTransactionRecords() {
                try {
                    const token = getToken();
                    if (!token) return;
                    
                    const startDate = document.getElementById('startDate').value;
                    const endDate = document.getElementById('endDate').value;
                    
                    console.log('加载交易记录，当前页:', currentPage);
                    console.log('交易类型:', transactionType);
                    
                    const baseUrl = window.location.origin;
                    const apiUrl = `${baseUrl}/v1/finance/transactions?page=${currentPage}&page_size=10&start_time=${startDate}&end_time=${endDate}&type=${transactionType}`;
                    console.log('API调用路径:', apiUrl);
                    
                    const response = await fetch(apiUrl, {
                        headers: {
                            'x-token': token,
                            'Content-Type': 'application/json'
                        }
                    });
                    
                    if (!response.ok) {
                        if (response.status === 401) {
                            handleTokenExpiration();
                            return;
                        }
                        throw new Error(`获取交易记录失败，状态码: ${response.status}`);
                    }
                    
                    const data = await response.json();
                    
                    // 兼容不同格式的响应
                    let listData = [];
                    let paginationInfo = { total: 0, page_size: 10 };
                    
                    if (data.code === 200 && data.data) {
                        listData = data.data.list || [];
                        paginationInfo = {
                            total: data.data.total || 0,
                            page_size: data.data.page_size || 10
                        };
                    } else if (data.list) {
                        listData = data.list;
                        paginationInfo = {
                            total: data.total || 0,
                            page_size: data.page_size || 10
                        };
                    }
                    
                    // 计算总页数
                    totalPages = Math.ceil(paginationInfo.total / paginationInfo.page_size);
                    
                    // 渲染交易记录
                    const recordsContainer = document.getElementById('transactionRecords');
                    recordsContainer.innerHTML = '';
                    
                    if (listData.length === 0) {
                        recordsContainer.innerHTML = `
                            <tr>
                                <td colspan="6" class="text-center text-muted">暂无交易记录</td>
                            </tr>
                        `;
                    } else {
                        listData.forEach(record => {
                            const typeClass = record.type === 'income' ? 'income-color' : 'expense-color';
                            const typeText = record.type === 'income' ? '收入' : '支出';
                            const statusClass = record.status === 'success' ? 'text-success' : (record.status === 'pending' ? 'text-warning' : 'text-danger');
                            const statusText = record.status === 'success' ? '成功' : (record.status === 'pending' ? '处理中' : '失败');
                            
                            const row = document.createElement('tr');
                            row.innerHTML = `
                                <td>${formatDate(record.create_time)}</td>
                                <td><span class="${typeClass}">${typeText}</span></td>
                                <td>${record.description || '-'}</td>
                                <td class="${typeClass} font-weight-semibold">${record.type === 'income' ? '+' : '-'}¥${formatNumber(record.amount || 0)}</td>
                                <td><span class="${statusClass}">${statusText}</span></td>
                                <td>${record.transaction_id || '-'}</td>
                            `;
                            recordsContainer.appendChild(row);
                        });
                    }
                    
                    // 渲染分页
                    renderPagination();
                } catch (error) {
                    console.error('加载交易记录失败:', error);
                    document.getElementById('transactionRecords').innerHTML = `
                        <tr>
                            <td colspan="6" class="text-center text-danger">加载失败: ${error.message}</td>
                        </tr>
                    `;
                }
            }
            
            // 渲染分页
            function renderPagination() {
                const pagination = document.getElementById('pagination');
                pagination.innerHTML = '';
                
                // 上一页
                const prevLi = document.createElement('li');
                prevLi.className = `page-item ${currentPage <= 1 ? 'disabled' : ''}`;
                prevLi.innerHTML = `
                    <a class="page-link" href="#" aria-label="Previous">
                        <span aria-hidden="true">&laquo;</span>
                    </a>
                `;
                prevLi.addEventListener('click', function(e) {
                    e.preventDefault();
                    if (currentPage > 1) {
                        currentPage--;
                        loadTransactionRecords();
                    }
                });
                pagination.appendChild(prevLi);
                
                // 页码
                const maxVisiblePages = 5;
                let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
                let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);
                
                if (endPage - startPage + 1 < maxVisiblePages) {
                    startPage = Math.max(1, endPage - maxVisiblePages + 1);
                }
                
                for (let i = startPage; i <= endPage; i++) {
                    const li = document.createElement('li');
                    li.className = `page-item ${i === currentPage ? 'active' : ''}`;
                    li.innerHTML = `<a class="page-link" href="#">${i}</a>`;
                    li.addEventListener('click', function(e) {
                        e.preventDefault();
                        if (i !== currentPage) {
                            currentPage = i;
                            loadTransactionRecords();
                        }
                    });
                    pagination.appendChild(li);
                }
                
                // 下一页
                const nextLi = document.createElement('li');
                nextLi.className = `page-item ${currentPage >= totalPages ? 'disabled' : ''}`;
                nextLi.innerHTML = `
                    <a class="page-link" href="#" aria-label="Next">
                        <span aria-hidden="true">&raquo;</span>
                    </a>
                `;
                nextLi.addEventListener('click', function(e) {
                    e.preventDefault();
                    if (currentPage < totalPages) {
                        currentPage++;
                        loadTransactionRecords();
                    }
                });
                pagination.appendChild(nextLi);
            }
            
            // 辅助函数：格式化日期
            function formatDate(dateString) {
                if (!dateString) return '';
                const date = new Date(dateString);
                return date.toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit'
                });
            }
            
            // 辅助函数：格式化数字
            function formatNumber(num) {
                return Number(num).toLocaleString('zh-CN', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                });
            }
        });
    </script>
</body>
</html>